package com.gitee.wsl.compose.ui.portal.bean

import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.runtime.Immutable
import com.gitee.wsl.compose.ui.portal.ComposePortal
import com.gitee.wsl.compose.ui.portal.PortalRendererState
import com.gitee.wsl.compose.ui.portal.nav.PortalBackstackState
import com.gitee.wsl.compose.ui.portal.toComposeTransition

@Immutable
internal data class ComposePortalEntry<KeyT>(
    val portal: ComposePortal<KeyT>,
    val wasContentPreviouslyVisible: Boolean,
    val isDisappearing: Boolean,
    val backstackState: PortalBackstackState,
    val rendererState: PortalRendererState,
    val enterTransitionOverride: EnterTransition?,
    val exitTransitionOverride: ExitTransition?,
    val uid: PortalEntry.Id,
) {
  val key: KeyT = portal.key

  companion object {
    fun <KeyT> fromPortalEntry(
        entry: PortalEntry<KeyT>,
        isDisappearing: Boolean,
    ) = ComposePortalEntry(
      portal = entry.portal as? ComposePortal<KeyT> ?: error("portal must be a ComposePortal"),
      wasContentPreviouslyVisible = entry.wasContentPreviouslyVisible,
      isDisappearing = isDisappearing,
      backstackState = entry.backstackState,
      rendererState = entry.rendererState,
      enterTransitionOverride = entry.enterTransitionOverride?.toComposeTransition(),
      exitTransitionOverride = entry.exitTransitionOverride?.toComposeTransition(),
      uid = entry.uid,
    )
  }
}


internal inline val <PortalKey> ComposePortalEntry<PortalKey>.isAttachedToComposition: Boolean
    get() = rendererState.isAddedOrAttached
